package com.sos.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sos.model.entity.*;
import com.sos.repository.HelperInfoRepository;
import com.sos.repository.HealthProfileRepository;
import com.sos.repository.NotificationRepository;
import com.sos.repository.RescueRecordRepository;
import com.sos.repository.SosHelperRepository;
import com.sos.repository.SosRequestRepository;
import com.sos.repository.SosResponseRepository;
import com.sos.repository.UserRepository;
import com.sos.util.GeoUtils;
import com.sos.util.JwtUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class WebSocketService extends TextWebSocketHandler {
    
    private final JwtUtils jwtUtils;
    private final UserRepository userRepository;
    private final HelperInfoRepository helperInfoRepository;
    private final SosRequestRepository sosRequestRepository;
    private final SosResponseRepository sosResponseRepository;
    private final SosHelperRepository sosHelperRepository;
    private final RescueRecordRepository rescueRecordRepository;
    private final NotificationRepository notificationRepository;
    private final UserOnlineStatusService userOnlineStatusService;
    private final UserLocationService userLocationService;
    private final HealthProfileRepository healthProfileRepository;
    private final RedisTemplate<String, Object> redisTemplate;
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    // 存储用户会话
    private final Map<String, WebSocketSession> userSessions = new ConcurrentHashMap<>();
    private final Map<String, Long> sessionUserMap = new ConcurrentHashMap<>();
    
    // 存储群聊会话，key为sosId，value为参与用户ID列表
    private final Map<Long, Set<Long>> chatGroups = new ConcurrentHashMap<>();
    
    // 存储群聊消息历史，key为sosId，value为消息列表
    private final Map<Long, List<Map<String, Object>>> chatMessages = new ConcurrentHashMap<>();
    
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String token = (String) session.getAttributes().get("token");
        String username = (String) session.getAttributes().get("username");
        
        if (token != null && username != null) {
            User user = userRepository.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            userSessions.put(username, session);
            sessionUserMap.put(session.getId(), user.getId());
            
            // 设置用户在线状态
            userOnlineStatusService.setUserOnline(user.getId(), username);
            
            // 更新帮助者信息中的在线状态
            HelperInfo helperInfo = helperInfoRepository.findByUserId(user.getId());
            if (helperInfo != null) {
                helperInfo.setOnlineStatus(1); // 设置为在线
                helperInfoRepository.save(helperInfo);
            }
            
            log.info("用户 {} 连接已建立，会话ID: {}", username, session.getId());
            
            // 发送连接成功消息，包含用户基本信息
            Map<String, Object> userInfo = Map.of(
                "userId", user.getId(),
                "username", user.getUsername(),
                "realName", user.getRealName(),
                "phone", user.getPhone(),
                "email", user.getEmail()
            );
            
            sendMessage(session, createMessage("连接成功", "连接成功", userInfo));
        }
    }
    
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        log.info("收到消息: {}", payload);
        
        try {
            Map<String, Object> data = objectMapper.readValue(payload, Map.class);
            // 修复类型转换问题，确保type字段可以处理字符串和整数类型
            Object typeObj = data.get("type");
            String type = typeObj != null ? typeObj.toString() : null;
            Long userId = sessionUserMap.get(session.getId());
            
            log.info("解析消息: type={}, userId={}", type, userId);
            
            if (userId == null) {
                log.error("无法获取用户ID，会话ID: {}", session.getId());
                sendMessage(session, createMessage("错误", "用户未正确连接"));
                return;
            }

            if (type != null) {
                switch (type) {
                    case "更新坐标":
                        updateLocation(userId, data);
                        break;
                    case "发起呼救请求":
                        handleSosRequest(userId, data);
                        break;
                    case "响应呼救请求", "帮助者响应":
                        handleSosResponse(userId, data);
                        break;
                    case "更新救援状态":
                        handleRescueRecordUpdate(userId, data);
                        break;
                    case "取消呼救请求":
                        handleSosCancel(userId, data);
                        break;
                    case "查询呼救请求":
                        handleQuerySosRequests(userId, data);
                        break;
                    case "查询收到的呼救请求":
                        handleQueryReceivedSosRequests(userId, data);
                        break;
                    case "查询呼救详情":
                        handleQuerySosDetails(userId, data);
                        break;
                    case "一键已读呼救请求":
                        handleMarkAllSosRequestsAsRead(userId, data);
                        break;
                    case "一键隐藏呼救请求":
                        handleHideAllSosRequests(userId, data);
                        break;
                    case "标记呼救请求已读":
                        handleMarkSosRequestAsRead(userId, data);
                        break;
                    case "标记呼救请求隐藏":
                        handleHideSosRequest(userId, data);
                        break;
                    case "标记收到的呼救请求已读":
                        handleMarkReceivedSosRequestAsRead(userId, data);
                        break;
                    case "标记收到的呼救请求隐藏":
                        handleHideReceivedSosRequest(userId, data);
                        break;
                    case "一键已读收到的呼救请求":
                        handleMarkAllReceivedSosRequestsAsRead(userId, data);
                        break;
                    case "一键隐藏收到的呼救请求":
                        handleHideAllReceivedSosRequests(userId, data);
                        break;
                    case "发送群聊消息":
                        handleGroupChatMessage(userId, data);
                        break;
                    case "获取群聊历史消息":
                        handleGetChatHistory(userId, data);
                        break;
                    case "心跳检测":
                        handleHeartbeat(userId);
                        break;
                    default:
                        log.warn("未知消息类型: {}", type);
                        sendMessage(session, createMessage("错误", "未知消息类型"));
                }
            }
        } catch (Exception e) {
            log.error("处理消息时出错", e);
            sendMessage(session, createMessage("错误", "消息处理失败: " + e.getMessage()));
        }
    }
    
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String sessionId = session.getId();
        Long userId = sessionUserMap.get(sessionId);
        
        if (userId != null) {
            // 设置用户离线
            userOnlineStatusService.setUserOffline(userId);
            
            // 更新帮助者信息中的在线状态
            HelperInfo helperInfo = helperInfoRepository.findByUserId(userId);
            if (helperInfo != null) {
                helperInfo.setOnlineStatus(0); // 设置为离线
                helperInfoRepository.save(helperInfo);
            }
            
            // 从会话映射中移除
            sessionUserMap.remove(sessionId);
            
            // 从用户会话映射中移除
            userSessions.values().removeIf(s -> s.getId().equals(sessionId));
            
            log.info("用户 {} 连接已关闭，状态: {}", userId, status);
        }
    }
    
    /**
     * 更新用户位置
     */
    private void updateLocation(Long userId, Map<String, Object> data) {
        try {
            BigDecimal latitude = new BigDecimal(data.get("latitude").toString());
            BigDecimal longitude = new BigDecimal(data.get("longitude").toString());
            
            // 更新位置信息
            userLocationService.updateUserLocation(userId, latitude, longitude);
            
            // 更新帮助者信息中的位置
            HelperInfo helperInfo = helperInfoRepository.findByUserId(userId);
            if (helperInfo != null) {
                helperInfo.setLastLatitude(latitude);
                helperInfo.setLastLongitude(longitude);
                helperInfo.setLastActiveTime(java.time.LocalDateTime.now());
                helperInfoRepository.save(helperInfo);
            }
            
            log.info("用户 {} 位置已更新: ({}, {})", userId, latitude, longitude);
        } catch (Exception e) {
            log.error("更新位置信息失败", e);
        }
    }
    
    /**
     * 处理一键已读呼救请求
     */
    private void handleSosRequest(Long userId, Map<String, Object> data) {
        try {
            User user = userRepository.findById(userId)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            // 创建SOS请求对象
            SosRequest sosRequest = new SosRequest();
            sosRequest.setUserId(userId);
            sosRequest.setLatitude(new BigDecimal(data.get("latitude").toString()));
            sosRequest.setLongitude(new BigDecimal(data.get("longitude").toString()));
            sosRequest.setLocationDesc((String) data.get("locationDesc"));
            sosRequest.setContent((String) data.get("content"));
            sosRequest.setType(parseStatusValue(data.get("sosType")));
            
            // 保存SOS请求
            SosRequest savedSos = sosRequestRepository.save(sosRequest);
            
            // 查找符合条件的帮助者
            List<HelperInfo> qualifiedHelpers = findQualifiedHelpers(savedSos);
            
            // 为每个帮助者创建SosHelper记录
            for (HelperInfo helper : qualifiedHelpers) {
                SosHelper sosHelper = new SosHelper();
                sosHelper.setSosId(savedSos.getId());
                sosHelper.setHelperId(helper.getUserId());
                sosHelper.setStatus(0); // 已邀请但未响应
                sosHelperRepository.save(sosHelper);
            }
            
            // 为求助者创建通知记录
            try {
                Notification notification = new Notification();
                notification.setUserId(userId);
                notification.setSosId(savedSos.getId());
                notification.setTitle("SOS求助已发送");
                notification.setContent("您的SOS求助已发送，共找到 " + qualifiedHelpers.size() + " 位附近帮助者");
                notificationRepository.save(notification);
                log.info("已为用户 {} 创建SOS请求通知，通知ID: {}", userId, notification.getId());
            } catch (Exception e) {
                log.error("创建SOS请求通知失败", e);
            }
            
            // 发送SOS响应给求助者，包含用户基本信息和SOS请求详细信息
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> userInfo = Map.of(
                    "userId", user.getId(),
                    "username", user.getUsername(),
                    "realName", user.getRealName()
                );

                Map<String, Object> sosRequestInfo = Map.of(
                    "latitude", savedSos.getLatitude(),      // 纬度
                    "longitude", savedSos.getLongitude(),    // 经度
                    "locationDesc", savedSos.getLocationDesc(), // 位置描述
                    "content", savedSos.getContent(),        // 内容
                    "type", savedSos.getType(),              // 类型
                    "status", savedSos.getStatus(),          // 状态
                    "createdTime", savedSos.getCreatedTime() != null ? savedSos.getCreatedTime().toString() : null // 创建时间
                );

                Map<String, Object> response = Map.of(
                    "type", "呼救请求反馈",
                    "sosId", savedSos.getId(),
                    "helpersCount", qualifiedHelpers.size(),
                    "message", "SOS请求已发送，找到 " + qualifiedHelpers.size() + " 位帮助者",
                    "userInfo", userInfo,
                    "sosRequestInfo", sosRequestInfo
                );
                sendMessage(requesterSession, response);
            }
            
            // 通知符合条件的帮助者
            notifyHelpers(qualifiedHelpers, savedSos, user);
            
            log.info("用户 {} 的SOS请求已处理，找到 {} 位帮助者", userId, qualifiedHelpers.size());
        } catch (Exception e) {
            log.error("处理SOS请求失败", e);
        }
    }

    /**
     * 处理SOS响应
     */
    private void handleSosResponse(Long userId, Map<String, Object> data) throws Exception {
        try {
            log.info("开始处理SOS响应: userId={}, data={}", userId, data);
            
            if (userId == null) {
                log.error("用户ID为空");
                throw new RuntimeException("用户未正确连接");
            }
            
            User helper = userRepository.findById(userId)
                    .orElseThrow(() -> {
                        log.error("未找到用户: userId={}", userId);
                        return new RuntimeException("用户不存在");
                    });
            
            Object sosIdObj = data.get("sosId");
            if (sosIdObj == null) {
                log.error("sosId为空");
                throw new RuntimeException("sosId不能为空");
            }
            
            Long sosId = Long.valueOf(sosIdObj.toString());
            
            Object statusObj = data.get("status");
            if (statusObj == null) {
                log.error("status为空");
                throw new RuntimeException("status不能为空");
            }
            
            // 修复NumberFormatException: 正确处理status字段可能是字符串或整数的情况
            Integer status = parseStatusValue(statusObj);
            
            log.info("解析SOS响应参数: sosId={}, status={}", sosId, status);
            
            // 验证SOS请求存在
            SosRequest sosRequest = sosRequestRepository.findById(sosId)
                    .orElseThrow(() -> {
                        log.error("未找到SOS请求: sosId={}", sosId);
                        return new RuntimeException("SOS请求不存在");
                    });
            
            log.info("找到SOS请求: sosId={}, currentStatus={}", sosId, sosRequest.getStatus());
            
            // 检查帮助者是否已关联到该SOS请求
            SosHelper sosHelper = sosHelperRepository.findBySosIdAndHelperId(sosId, userId)
                    .orElseThrow(() -> {
                        log.error("帮助者未被邀请参与此SOS请求: sosId={}, userId={}", sosId, userId);
                        return new RuntimeException("您未被邀请参与此SOS请求");
                    });
            
            log.info("找到SosHelper记录: id={}, 当前状态={}", sosHelper.getId(), sosHelper.getStatus());
            
            // 检查是否已响应过
            if (sosHelper.getStatus() != 0) {
                log.error("帮助者已响应过此SOS请求: sosId={}, userId={}, currentStatus={}", sosId, userId, sosHelper.getStatus());
                throw new RuntimeException("不能重复响应");
            }
            
            // 更新帮助者状态
            sosHelper.setStatus(status);
            sosHelperRepository.save(sosHelper);
            log.info("已更新SosHelper状态为: {}", status);
            
            // 保存响应记录（用于历史记录）
            SosResponse response = new SosResponse();
            response.setSosId(sosId);
            response.setHelperId(userId);
            response.setStatus(status);
            SosResponse savedResponse = sosResponseRepository.save(response);
            log.info("已创建SosResponse记录: id={}", savedResponse.getId());
            
            // 处理接受救援的情况
            if (status == 1) {
                log.info("处理接受救援的响应");
                // 通知求助者有帮助者接受了请求
                try {
                    Map<String, Object> userInfo = Map.of(
                        "userId", helper.getId(),
                        "username", helper.getUsername(),
                        "realName", helper.getRealName()
                    );
                    
                    // 统计已接受的帮助者数量
                    long acceptedHelpersCount = sosHelperRepository.countBySosIdAndStatus(sosId, 1);
                    
                    Map<String, Object> notification = Map.of(
                        "type", "帮助者响应",
                        "sosId", sosRequest.getId(),
                        "helperId", userId,
                        "helperName", helper.getUsername(),
                        "status", "accepted",
                        "acceptedHelpersCount", acceptedHelpersCount,
                        "timestamp", System.currentTimeMillis(),
                        "userInfo", userInfo
                    );
                    
                    WebSocketSession requesterSession = getUserSession(sosRequest.getUserId());
                    if (requesterSession != null && requesterSession.isOpen()) {
                        sendMessage(requesterSession, notification);
                        log.info("已向求助者发送帮助者响应通知");
                    } else {
                        log.warn("无法向求助者发送帮助者响应通知: 会话不存在或已关闭");
                    }
                } catch (Exception e) {
                    log.error("通过WebSocket通知求助者失败", e);
                }
                
                // 当有人接受请求时，检查是否需要初始化群聊或添加成员
                if (chatGroups.containsKey(sosId)) {
                    // 群聊已存在，添加新成员
                    addMemberToChatGroup(sosId, userId);
                } else {
                    // 初始化群聊
                    initializeChatGroup(sosId, sosRequest.getUserId(), userId);
                }
            } else if (status == 2) {
                log.info("处理拒绝救援的响应");
                // 拒绝救援请求，通过WebSocket通知求助者
                try {
                    Map<String, Object> userInfo = Map.of(
                        "userId", helper.getId(),
                        "username", helper.getUsername(),
                        "realName", helper.getRealName()
                    );
                    
                    Map<String, Object> notification = Map.of(
                        "type", "帮助者响应",
                        "sosId", sosRequest.getId(),
                        "helperId", userId,
                        "status", "rejected",
                        "timestamp", System.currentTimeMillis(),
                        "userInfo", userInfo
                    );
                    
                    WebSocketSession requesterSession = getUserSession(sosRequest.getUserId());
                    if (requesterSession != null && requesterSession.isOpen()) {
                        sendMessage(requesterSession, notification);
                        log.info("已向求助者发送帮助者拒绝通知");
                    } else {
                        log.warn("无法向求助者发送帮助者拒绝通知: 会话不存在或已关闭");
                    }
                } catch (Exception e) {
                    log.error("通过WebSocket通知求助者失败", e);
                }
            }
            
            // 向帮助者发送响应确认
            WebSocketSession helperSession = getUserSession(userId);
            if (helperSession != null && helperSession.isOpen()) {
                Map<String, Object> userInfo = Map.of(
                    "userId", helper.getId(),
                    "username", helper.getUsername(),
                    "realName", helper.getRealName()
                );
                
                sendMessage(helperSession, Map.of(
                    "type", "响应确认",
                    "message", "响应已成功提交",
                    "userInfo", userInfo
                ));
                log.info("已向帮助者发送响应确认");
            } else {
                log.warn("无法向帮助者发送响应确认: 会话不存在或已关闭");
            }
            
        } catch (Exception e) {
            log.error("处理SOS响应失败: userId={}, data={}", userId, data, e);
            
            // 向帮助者发送错误信息
            WebSocketSession helperSession = getUserSession(userId);
            if (helperSession != null && helperSession.isOpen()) {
                sendMessage(helperSession, Map.of(
                    "type", "错误",
                    "message", "处理响应失败: " + e.getMessage()
                ));
                log.info("已向帮助者发送错误信息");
            } else {
                log.warn("无法向帮助者发送错误信息: 会话不存在或已关闭");
            }
            // 重新抛出异常以便上层捕获
            throw e;
        }
    }
    
    /**
     * 查找符合条件的帮助者
     */
    private List<HelperInfo> findQualifiedHelpers(SosRequest sosRequest) {
        Long requesterId = sosRequest.getUserId();
        BigDecimal requesterLat = sosRequest.getLatitude();
        BigDecimal requesterLon = sosRequest.getLongitude();
        
        // 获取所有在线帮助者
        List<HelperInfo> onlineHelpers = helperInfoRepository.findByOnlineStatus(1);
        
        return onlineHelpers.stream()
                .filter(helper -> {
                    // 排除求助者自己
                    if (helper.getUserId().equals(requesterId)) {
                        return false;
                    }
                    
                    // 检查用户是否愿意帮助他人
                    User helperUser = userRepository.findById(helper.getUserId()).orElse(null);
                    if (helperUser == null || helperUser.getCanHelp() != 1) {
                        return false;
                    }
                    
                    // 获取帮助者位置
                    BigDecimal helperLat = helper.getLastLatitude();
                    BigDecimal helperLon = helper.getLastLongitude();
                    
                    // 检查位置信息是否完整
                    if (helperLat == null || helperLon == null) {
                        return false;
                    }
                    
                    // 计算距离并检查是否在服务范围内
                    double distance = GeoUtils.calculateDistance(requesterLat, requesterLon, helperLat, helperLon);
                    return distance <= helper.getServiceRadius();
                })
                .collect(Collectors.toList());
    }
    
    /**
     * 通知帮助者
     */
    private void notifyHelpers(List<HelperInfo> helpers, SosRequest sosRequest, User requester) {
        log.info("开始通知帮助者: helpersCount={}, sosId={}", helpers.size(), sosRequest.getId());
        
        // 构建求助者信息
        Map<String, Object> requesterInfo = Map.of(
            "userId", requester.getId(),
            "username", requester.getUsername(),
            "realName", requester.getRealName()
        );
        
        for (HelperInfo helper : helpers) {
            try {
                log.info("准备通知帮助者: 用户ID={}", helper.getUserId());
                WebSocketSession helperSession = getUserSession(helper.getUserId());
                if (helperSession != null && helperSession.isOpen()) {
                    log.info("帮助者 {} 已连接到WebSocket，准备发送通知", helper.getUserId());
                    Map<String, Object> notification = Map.of(
                        "type", "SOS通知",
                        "sosId", sosRequest.getId(),
                        "userId", sosRequest.getUserId(),
                        "latitude", sosRequest.getLatitude(),
                        "longitude", sosRequest.getLongitude(),
                        "locationDesc", sosRequest.getLocationDesc(),
                        "content", sosRequest.getContent(),
                        "sosType", sosRequest.getType(), // 修改键名为sosType避免冲突
                        "timestamp", System.currentTimeMillis(),
                        "requesterInfo", requesterInfo  // 添加求助者信息
                    );
                    sendMessage(helperSession, notification);
                    log.info("已向帮助者 {} 发送SOS通知", helper.getUserId());
                } else {
                    if (helperSession == null) {
                        log.warn("帮助者 {} 没有活跃的WebSocket会话", helper.getUserId());
                    } else if (!helperSession.isOpen()) {
                        log.warn("帮助者 {} 的WebSocket会话未打开", helper.getUserId());
                    }
                }
            } catch (Exception e) {
                log.error("通知帮助者 {} 失败", helper.getUserId(), e);
            }
        }
        log.info("完成通知所有帮助者");
    }
    
    /**
     * 处理心跳包
     */
    private void handleHeartbeat(Long userId) {
        try {
            userOnlineStatusService.refreshUserOnlineStatus(userId);
            log.debug("用户 {} 心跳包处理完成", userId);
        } catch (Exception e) {
            log.error("处理心跳包失败", e);
        }
    }
    
    /**
     * 处理查询呼救请求
     */
    private void handleQuerySosRequests(Long userId, Map<String, Object> data) {
        try {
            log.info("开始处理用户 {} 的查询呼救请求", userId);
            
            // 查询该用户发起的所有SOS请求
            List<SosRequest> sosRequests = sosRequestRepository.findByUserId(userId);
            
            // 准备响应数据
            List<Map<String, Object>> requestDataList = sosRequests.stream().map(sosRequest -> {
                Map<String, Object> requestData = new HashMap<>();
                requestData.put("id", sosRequest.getId());                           // 求助ID
                requestData.put("userId", sosRequest.getUserId());                  // 用户ID
                requestData.put("latitude", sosRequest.getLatitude());              // 纬度
                requestData.put("longitude", sosRequest.getLongitude());            // 经度
                requestData.put("locationDesc", sosRequest.getLocationDesc());      // 位置描述
                requestData.put("content", sosRequest.getContent());                // 内容
                requestData.put("type", sosRequest.getType());                      // 呼救类型(1:医疗,2:事故,3:治安,4:其他)
                requestData.put("status", sosRequest.getStatus());                  // 状态(0:待处理,1:处理中,2:已解决,3:已取消)
                requestData.put("isRead", sosRequest.getIsRead());                  // 是否已读
                requestData.put("isHidden", sosRequest.getIsHidden());              // 是否隐藏
                
                // Format LocalDateTime objects as strings to avoid serialization issues
                requestData.put("acceptTime", sosRequest.getAcceptTime() != null ? sosRequest.getAcceptTime().toString() : null);    // 接受帮助时间
                requestData.put("solveTime", sosRequest.getSolveTime() != null ? sosRequest.getSolveTime().toString() : null);      // 解决时间
                requestData.put("createdTime", sosRequest.getCreatedTime() != null ? sosRequest.getCreatedTime().toString() : null); // 创建时间
                requestData.put("updatedTime", sosRequest.getUpdatedTime() != null ? sosRequest.getUpdatedTime().toString() : null); // 更新时间
                
                return requestData;
            }).collect(Collectors.toList());
            
            // 发送查询结果给用户
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> response = new HashMap<>();
                response.put("type", "呼救请求查询结果");
                response.put("data", requestDataList);
                response.put("count", requestDataList.size());
                response.put("timestamp", System.currentTimeMillis());
                
                try {
                    sendMessage(requesterSession, response);
                    log.info("已向用户 {} 发送呼救请求查询结果，共 {} 条记录", userId, requestDataList.size());
                } catch (Exception e) {
                    log.error("发送呼救请求查询结果给用户 {} 失败", userId, e);
                }
            } else {
                if (requesterSession == null) {
                    log.warn("未找到用户 {} 的WebSocket会话", userId);
                } else if (!requesterSession.isOpen()) {
                    log.warn("用户 {} 的WebSocket会话未打开", userId);
                }
            }
        } catch (Exception e) {
            log.error("处理查询呼救请求失败", e);
            
            // 向用户发送错误信息
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("type", "错误");
                errorResponse.put("message", "查询呼救请求失败: " + e.getMessage());
                
                try {
                    sendMessage(requesterSession, errorResponse);
                } catch (Exception sendException) {
                    log.error("发送错误信息给用户 {} 失败", userId, sendException);
                }
            }
        }
    }

    /**
     * 处理救援记录更新
     */
    private void handleRescueRecordUpdate(Long userId, Map<String, Object> data) throws Exception {
        try {
            log.info("开始处理用户 {} 的救援记录更新请求", userId);
            
            User helper = userRepository.findById(userId)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            // 获取参数
            Long sosId = Long.valueOf(data.get("sosId").toString());
            // 修复NumberFormatException: 正确处理status字段可能是字符串或整数的情况
            Integer status = parseStatusValue(data.get("status"));
            String content = (String) data.get("content");
            
            // 验证SOS请求存在
            SosRequest sosRequest = sosRequestRepository.findById(sosId)
                    .orElseThrow(() -> new RuntimeException("SOS请求不存在"));
            
            // 验证帮助者是否已接受该SOS请求
            SosHelper sosHelper = sosHelperRepository.findBySosIdAndHelperId(sosId, userId)
                    .orElseThrow(() -> new RuntimeException("您未参与此SOS请求"));
            
            if (sosHelper.getStatus() != 1) {
                throw new RuntimeException("您未接受此SOS请求");
            }
            
            // 创建救援记录
            RescueRecord record = new RescueRecord();
            record.setSosId(sosId);
            record.setHelperId(userId);
            record.setContent(content != null ? content : getDefaultContent(status));
            record.setStatus(status);
            rescueRecordRepository.save(record);
            log.info("已创建救援记录，ID: {}", record.getId());
            
            // 通过WebSocket通知求助者状态更新
            try {
                Map<String, Object> userInfo = Map.of(
                    "userId", helper.getId(),
                    "username", helper.getUsername(),
                    "realName", helper.getRealName()
                );
                
                Map<String, Object> notification = Map.of(
                    "type", "救援状态更新",
                    "sosId", sosId,
                    "status", status,
                    "statusDescription", getStatusDescription(status),
                    "content", content != null ? content : getDefaultContent(status),
                    "helperId", userId,
                    "helperName", helper.getUsername(),
                    "timestamp", System.currentTimeMillis(),
                    "userInfo", userInfo
                );
                
                WebSocketSession requesterSession = getUserSession(sosRequest.getUserId());
                if (requesterSession != null && requesterSession.isOpen()) {
                    sendMessage(requesterSession, notification);
                    log.info("已通知求助者 {} 状态更新", sosRequest.getUserId());
                } else {
                    log.warn("无法通知求助者 {} 状态更新，会话不存在或已关闭", sosRequest.getUserId());
                }
            } catch (Exception e) {
                log.error("通过WebSocket通知求助者状态更新失败", e);
            }
            
            // 如果状态为已解决，更新帮助者信息和SosHelper状态
            if (status == 4) {
                // 更新SosHelper状态为已完成
                sosHelper.setStatus(3); // 已完成
                sosHelperRepository.save(sosHelper);
                
                HelperInfo helperInfo = helperInfoRepository.findByUserId(userId);
                if (helperInfo != null) {
                    helperInfo.setHelpCount(helperInfo.getHelpCount() + 1);
                    helperInfoRepository.save(helperInfo);
                    log.info("已更新帮助者 {} 的帮助次数", userId);
                }
                
                // 通知所有相关方救援已完成
                try {
                    Map<String, Object> userInfo = Map.of(
                        "userId", helper.getId(),
                        "username", helper.getUsername(),
                        "realName", helper.getRealName()
                    );
                    
                    Map<String, Object> notification = Map.of(
                        "type", "救援完成",
                        "sosId", sosId,
                        "helperId", userId,
                        "helperName", helper.getUsername(),
                        "timestamp", System.currentTimeMillis(),
                        "userInfo", userInfo
                    );
                    
                    // 通知求助者
                    WebSocketSession requesterSession = getUserSession(sosRequest.getUserId());
                    if (requesterSession != null && requesterSession.isOpen()) {
                        sendMessage(requesterSession, notification);
                        log.info("已通知求助者 {} 救援完成", sosRequest.getUserId());
                    }
                    
                    // 通知帮助者
                    WebSocketSession helperSession = getUserSession(userId);
                    if (helperSession != null && helperSession.isOpen()) {
                        sendMessage(helperSession, notification);
                        log.info("已通知帮助者 {} 救援完成", userId);
                    }
                } catch (Exception e) {
                    log.error("通过WebSocket通知救援完成失败", e);
                }
            }
            
            // 向帮助者发送确认消息
            WebSocketSession helperSession = getUserSession(userId);
            if (helperSession != null && helperSession.isOpen()) {
                Map<String, Object> userInfo = Map.of(
                    "userId", helper.getId(),
                    "username", helper.getUsername(),
                    "realName", helper.getRealName()
                );
                
                sendMessage(helperSession, Map.of(
                    "type", "救援记录更新确认",
                    "message", "救援记录更新成功",
                    "userInfo", userInfo
                ));
                log.info("已向帮助者 {} 发送更新确认", userId);
            }
        } catch (Exception e) {
            log.error("处理救援记录更新失败", e);
            
            // 向帮助者发送错误信息
            WebSocketSession helperSession = getUserSession(userId);
            if (helperSession != null && helperSession.isOpen()) {
                sendMessage(helperSession, Map.of(
                    "type", "错误",
                    "message", "救援记录更新失败: " + e.getMessage()
                ));
            }
        }
    }
    
    /**
     * 处理SOS取消请求
     */
    private void handleSosCancel(Long userId, Map<String, Object> data) throws Exception {
        try {
            log.info("开始处理用户 {} 的SOS取消请求", userId);
            
            User requester = userRepository.findById(userId)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            // 获取参数
            Long sosId = Long.valueOf(data.get("sosId").toString());
            
            // 验证SOS请求存在且是由该用户发起
            SosRequest sosRequest = sosRequestRepository.findById(sosId)
                    .orElseThrow(() -> new RuntimeException("SOS请求不存在"));
            
            if (!sosRequest.getUserId().equals(userId)) {
                throw new RuntimeException("无权取消此SOS请求");
            }
            
            // 检查SOS状态是否可以取消（只有在没有帮助者接受的情况下才能取消）
            long acceptedHelpersCount = sosHelperRepository.countBySosIdAndStatus(sosId, 1);
            if (acceptedHelpersCount > 0) {
                throw new RuntimeException("已有帮助者接受请求，无法取消");
            }
            
            // 更新SOS请求状态为已取消
            sosRequest.setStatus(3); // 3表示已取消
            sosRequest.setSolveTime(LocalDateTime.now());
            sosRequestRepository.save(sosRequest);
            log.info("已取消SOS请求 {}", sosId);
            
            // 向请求者发送确认消息
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> userInfo = Map.of(
                    "userId", requester.getId(),
                    "username", requester.getUsername(),
                    "realName", requester.getRealName()
                );
                
                sendMessage(requesterSession, Map.of(
                    "type", "SOS取消确认",
                    "sosId", sosId,
                    "message", "SOS请求已成功取消",
                    "userInfo", userInfo
                ));
                log.info("已向请求者 {} 发送取消确认", userId);
            }
            
            // 通知已经收到通知的帮助者SOS已被取消
            List<SosHelper> sosHelpers = sosHelperRepository.findBySosId(sosId);
            for (SosHelper sosHelper : sosHelpers) {
                try {
                    WebSocketSession helperSession = getUserSession(sosHelper.getHelperId());
                    if (helperSession != null && helperSession.isOpen()) {
                        Map<String, Object> userInfo = Map.of(
                            "userId", requester.getId(),
                            "username", requester.getUsername(),
                            "realName", requester.getRealName()
                        );
                        
                        sendMessage(helperSession, Map.of(
                            "type", "SOS已取消",
                            "sosId", sosId,
                            "message", "SOS请求已被发起者取消",
                            "userInfo", userInfo
                        ));
                        log.info("已通知帮助者 {} SOS请求已取消", sosHelper.getHelperId());
                    }
                } catch (Exception e) {
                    log.error("通知帮助者 {} SOS取消失败", sosHelper.getHelperId(), e);
                }
            }
            
        } catch (Exception e) {
            log.error("处理SOS取消失败", e);
            
            // 向请求者发送错误信息
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                sendMessage(requesterSession, Map.of(
                    "type", "错误",
                    "message", "SOS取消失败: " + e.getMessage()
                ));
            }
        }
    }
    
    /**
     * 处理查询收到的呼救请求
     */
    private void handleQueryReceivedSosRequests(Long userId, Map<String, Object> data) {
        try {
            log.info("开始处理用户 {} 的查询收到的呼救请求", userId);
            
            // 查询该用户作为帮助者参与的所有SOS请求
            List<SosHelper> sosHelpers = sosHelperRepository.findByHelperId(userId);
            
            // 获取这些SOS请求的详细信息
            List<Map<String, Object>> requestDataList = sosHelpers.stream().map(sosHelper -> {
                SosRequest sosRequest = sosRequestRepository.findById(sosHelper.getSosId()).orElse(null);
                if (sosRequest == null) {
                    return null;
                }
                
                Map<String, Object> requestData = new HashMap<>();
                requestData.put("id", sosRequest.getId());
                requestData.put("userId", sosRequest.getUserId());
                requestData.put("latitude", sosRequest.getLatitude());
                requestData.put("longitude", sosRequest.getLongitude());
                requestData.put("locationDesc", sosRequest.getLocationDesc());
                requestData.put("content", sosRequest.getContent());
                requestData.put("type", sosRequest.getType());
                requestData.put("status", sosRequest.getStatus());
                requestData.put("isRead", sosRequest.getIsRead());
                requestData.put("isHidden", sosRequest.getIsHidden());
                requestData.put("helperStatus", sosHelper.getStatus()); // 帮助者对该请求的状态
                requestData.put("helperIsRead", sosHelper.getIsRead()); // 帮助者是否已读该请求
                requestData.put("helperIsHidden", sosHelper.getIsHidden()); // 帮助者是否隐藏该请求
                
                // Format LocalDateTime objects as strings to avoid serialization issues
                requestData.put("acceptTime", sosRequest.getAcceptTime() != null ? sosRequest.getAcceptTime().toString() : null);
                requestData.put("solveTime", sosRequest.getSolveTime() != null ? sosRequest.getSolveTime().toString() : null);
                requestData.put("createdTime", sosRequest.getCreatedTime() != null ? sosRequest.getCreatedTime().toString() : null);
                requestData.put("updatedTime", sosRequest.getUpdatedTime() != null ? sosRequest.getUpdatedTime().toString() : null);
                
                // 添加求助者信息
                User requester = userRepository.findById(sosRequest.getUserId()).orElse(null);
                if (requester != null) {
                    Map<String, Object> requesterInfo = new HashMap<>();
                    requesterInfo.put("userId", requester.getId());
                    requesterInfo.put("username", requester.getUsername());
                    requesterInfo.put("realName", requester.getRealName());
                    requestData.put("requesterInfo", requesterInfo);
                }
                
                return requestData;
            }).filter(Objects::nonNull).collect(Collectors.toList());
            
            // 发送查询结果给用户
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> response = new HashMap<>();
                response.put("type", "查询收到的呼救请求结果");
                response.put("data", requestDataList);
                response.put("count", requestDataList.size());
                response.put("timestamp", System.currentTimeMillis());
                
                try {
                    sendMessage(requesterSession, response);
                    log.info("已向用户 {} 发送收到的呼救请求查询结果，共 {} 条记录", userId, requestDataList.size());
                } catch (Exception e) {
                    log.error("发送收到的呼救请求查询结果给用户 {} 失败", userId, e);
                }
            } else {
                if (requesterSession == null) {
                    log.warn("未找到用户 {} 的WebSocket会话", userId);
                } else if (!requesterSession.isOpen()) {
                    log.warn("用户 {} 的WebSocket会话未打开", userId);
                }
            }
        } catch (Exception e) {
            log.error("处理查询收到的呼救请求失败", e);
            
            // 向用户发送错误信息
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("type", "错误");
                errorResponse.put("message", "查询收到的呼救请求失败: " + e.getMessage());
                
                try {
                    sendMessage(requesterSession, errorResponse);
                } catch (Exception sendException) {
                    log.error("发送错误信息给用户 {} 失败", userId, sendException);
                }
            }
        }
    }

    /**
     * 处理查询呼救详情
     */
    private void handleQuerySosDetails(Long userId, Map<String, Object> data) {
        try {
            log.info("开始处理用户 {} 的查询呼救详情请求", userId);

            // 获取请求参数
            Object sosIdObj = data.get("sosId");
            if (sosIdObj == null) {
                throw new RuntimeException("sosId不能为空");
            }

            Long sosId = Long.valueOf(sosIdObj.toString());

            // 验证SOS请求存在
            SosRequest sosRequest = sosRequestRepository.findById(sosId)
                    .orElseThrow(() -> new RuntimeException("SOS请求不存在"));

            // 构建响应数据
            Map<String, Object> responseData = new HashMap<>();
            
            // 添加SOS请求基本信息
            responseData.put("id", sosRequest.getId());
            responseData.put("userId", sosRequest.getUserId());
            responseData.put("latitude", sosRequest.getLatitude());
            responseData.put("longitude", sosRequest.getLongitude());
            responseData.put("locationDesc", sosRequest.getLocationDesc());
            responseData.put("content", sosRequest.getContent());
            responseData.put("type", sosRequest.getType());
            responseData.put("responseStatus", sosRequest.getStatus());

            
            // 添加时间信息
            responseData.put("acceptTime", sosRequest.getAcceptTime() != null ? sosRequest.getAcceptTime().toString() : null);
            responseData.put("solveTime", sosRequest.getSolveTime() != null ? sosRequest.getSolveTime().toString() : null);
            responseData.put("createdTime", sosRequest.getCreatedTime() != null ? sosRequest.getCreatedTime().toString() : null);
            responseData.put("updatedTime", sosRequest.getUpdatedTime() != null ? sosRequest.getUpdatedTime().toString() : null);

            // 添加发起者信息
            User requester = userRepository.findById(sosRequest.getUserId()).orElse(null);
            if (requester != null) {
                Map<String, Object> requesterInfo = new HashMap<>();
                requesterInfo.put("userId", requester.getId());
                requesterInfo.put("username", requester.getUsername());
                requesterInfo.put("realName", requester.getRealName());
                requesterInfo.put("phone", requester.getPhone());
                requesterInfo.put("email", requester.getEmail());
                requesterInfo.put("avatar", requester.getAvatar());
                responseData.put("requesterInfo", requesterInfo);
            }

            // 添加健康档案信息
            HealthProfile healthProfile = healthProfileRepository.findByUserId(sosRequest.getUserId()).orElse(null);
            if (healthProfile != null) {
                Map<String, Object> healthProfileInfo = new HashMap<>();
                healthProfileInfo.put("bloodType", healthProfile.getBloodType());
                healthProfileInfo.put("allergies", healthProfile.getAllergies());
                healthProfileInfo.put("medicalConditions", healthProfile.getMedicalConditions());
                healthProfileInfo.put("medications", healthProfile.getMedications());
                healthProfileInfo.put("emergencyContactName", healthProfile.getEmergencyContactName());
                healthProfileInfo.put("emergencyContactPhone", healthProfile.getEmergencyContactPhone());
                healthProfileInfo.put("height", healthProfile.getHeight());
                healthProfileInfo.put("weight", healthProfile.getWeight());
                healthProfileInfo.put("additionalInfo", healthProfile.getAdditionalInfo());
                responseData.put("healthProfile", healthProfileInfo);
            } else {
                responseData.put("healthProfile", null);
            }

            // 添加当前用户（帮助者）的信息
            SosHelper currentUserHelper = sosHelperRepository.findBySosIdAndHelperId(sosId, userId).orElse(null);
            if (currentUserHelper != null) {
                responseData.put("currentUserHelperStatus", currentUserHelper.getStatus());
                responseData.put("currentUserIsRead", currentUserHelper.getIsRead());
                responseData.put("currentUserIsHidden", currentUserHelper.getIsHidden());
                responseData.put("currentUserHelperCreatedTime", currentUserHelper.getCreatedTime() != null ? currentUserHelper.getCreatedTime().toString() : null);
                responseData.put("currentUserHelperUpdatedTime", currentUserHelper.getUpdatedTime() != null ? currentUserHelper.getUpdatedTime().toString() : null);
            }

            // 添加志愿者信息（包括当前用户和其他帮助者）
            List<SosHelper> sosHelpers = sosHelperRepository.findBySosId(sosId);
            List<Map<String, Object>> helpersData = sosHelpers.stream().map(sosHelper -> {
                User helperUser = userRepository.findById(sosHelper.getHelperId()).orElse(null);
                if (helperUser == null) {
                    return null;
                }

                Map<String, Object> helperData = new HashMap<>();
                helperData.put("userId", helperUser.getId());
                helperData.put("username", helperUser.getUsername());
                helperData.put("phone", helperUser.getPhone());
                helperData.put("realName", helperUser.getRealName());
                helperData.put("avatar", helperUser.getAvatar());
                helperData.put("helperStatus", sosHelper.getStatus()); // 响应状态
                helperData.put("helperIsRead", sosHelper.getIsRead());
                helperData.put("helperIsHidden", sosHelper.getIsHidden());
                helperData.put("helperCreatedTime", sosHelper.getCreatedTime() != null ? sosHelper.getCreatedTime().toString() : null);
                helperData.put("helperUpdatedTime", sosHelper.getUpdatedTime() != null ? sosHelper.getUpdatedTime().toString() : null);

                return helperData;
            }).filter(Objects::nonNull).collect(Collectors.toList());
            
            responseData.put("helpers", helpersData);

            // 添加救援记录信息
            List<RescueRecord> rescueRecords = rescueRecordRepository.findBySosId(sosId);
            List<Map<String, Object>> rescueRecordsData = rescueRecords.stream().map(record -> {
                Map<String, Object> recordData = new HashMap<>();
                recordData.put("id", record.getId());
                recordData.put("helperId", record.getHelperId());
                recordData.put("content", record.getContent());
                recordData.put("status", record.getStatus());
                recordData.put("createdTime", record.getCreatedTime() != null ? record.getCreatedTime().toString() : null);
                
                // 添加帮助者信息
                User helperUser = userRepository.findById(record.getHelperId()).orElse(null);
                if (helperUser != null) {
                    Map<String, Object> helperInfo = new HashMap<>();
                    helperInfo.put("userId", helperUser.getId());
                    helperInfo.put("username", helperUser.getUsername());
                    helperInfo.put("realName", helperUser.getRealName());
                    helperInfo.put("avatar", helperUser.getAvatar());
                    recordData.put("helperInfo", helperInfo);
                }
                
                return recordData;
            }).collect(Collectors.toList());
            
            responseData.put("rescueRecords", rescueRecordsData);

            // 发送查询结果给用户
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> response = new HashMap<>();
                response.put("type", "呼救详情查询结果");
                response.put("data", responseData);
                response.put("timestamp", System.currentTimeMillis());

                try {
                    sendMessage(requesterSession, response);
                    log.info("已向用户 {} 发送呼救详情查询结果，SOS ID: {}", userId, sosId);
                    log.info(" 发送呼救详情查询结果，SOS ID: {},详细信息{}", userId, response);
                } catch (Exception e) {
                    log.error("发送呼救详情查询结果给用户 {} 失败", userId, e);
                }
            } else {
                if (requesterSession == null) {
                    log.warn("未找到用户 {} 的WebSocket会话", userId);
                } else if (!requesterSession.isOpen()) {
                    log.warn("用户 {} 的WebSocket会话未打开", userId);
                }
            }
        } catch (Exception e) {
            log.error("处理查询呼救详情失败", e);

            // 向用户发送错误信息
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("type", "错误");
                errorResponse.put("message", "查询呼救详情失败: " + e.getMessage());

                try {
                    sendMessage(requesterSession, errorResponse);
                } catch (Exception sendException) {
                    log.error("发送错误信息给用户 {} 失败", userId, sendException);
                }
            }
        }
    }

    /**
     * 处理一键已读呼救请求
     */
    private void handleMarkAllSosRequestsAsRead(Long userId, Map<String, Object> data) {
        try {
            log.info("开始处理用户 {} 的一键已读呼救请求", userId);
            
            // 将该用户发起的所有SOS请求标记为已读
            List<SosRequest> sosRequests = sosRequestRepository.findByUserId(userId);
            int updatedCount = 0;
            
            for (SosRequest sosRequest : sosRequests) {
                // 只更新未读的请求
                if (sosRequest.getIsRead() == 0) {
                    sosRequest.setIsRead(1);
                    sosRequestRepository.save(sosRequest);
                    updatedCount++;
                }
            }
            
            // 发送处理结果给用户
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> response = new HashMap<>();
                response.put("type", "一键已读呼救请结果");
                response.put("message", "成功将 " + updatedCount + " 条呼救请求标记为已读");
                response.put("updatedCount", updatedCount);
                response.put("timestamp", System.currentTimeMillis());
                
                try {
                    sendMessage(requesterSession, response);
                    log.info("已向用户 {} 发送一键已读处理结果，共更新 {} 条记录", userId, updatedCount);
                } catch (Exception e) {
                    log.error("发送一键已读处理结果给用户 {} 失败", userId, e);
                }
            }
        } catch (Exception e) {
            log.error("处理一键已读呼救请求失败", e);
            
            // 向用户发送错误信息
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("type", "错误");
                errorResponse.put("message", "一键已读处理失败: " + e.getMessage());
                
                try {
                    sendMessage(requesterSession, errorResponse);
                } catch (Exception sendException) {
                    log.error("发送错误信息给用户 {} 失败", userId, sendException);
                }
            }
        }
    }
    
    /**
     * 处理一键隐藏呼救请求
     */
    private void handleHideAllSosRequests(Long userId, Map<String, Object> data) {
        try {
            log.info("开始处理用户 {} 的一键隐藏呼救请求", userId);
            
            // 将该用户发起的所有SOS请求标记为隐藏
            List<SosRequest> sosRequests = sosRequestRepository.findByUserId(userId);
            int hiddenCount = 0;
            
            for (SosRequest sosRequest : sosRequests) {
                // 只更新未隐藏的请求
                if (sosRequest.getIsHidden() == 0) {
                    sosRequest.setIsHidden(1);
                    sosRequestRepository.save(sosRequest);
                    hiddenCount++;
                }
            }
            
            // 发送处理结果给用户
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> response = new HashMap<>();
                response.put("type", "一键隐藏呼救请结果");
                response.put("message", "成功将 " + hiddenCount + " 条呼救请求标记为隐藏");
                response.put("hiddenCount", hiddenCount);
                response.put("timestamp", System.currentTimeMillis());
                
                try {
                    sendMessage(requesterSession, response);
                    log.info("已向用户 {} 发送一键隐藏处理结果，共隐藏 {} 条记录", userId, hiddenCount);
                } catch (Exception e) {
                    log.error("发送一键隐藏处理结果给用户 {} 失败", userId, e);
                }
            }
        } catch (Exception e) {
            log.error("处理一键隐藏呼救请求失败", e);
            
            // 向用户发送错误信息
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("type", "错误");
                errorResponse.put("message", "一键隐藏处理失败: " + e.getMessage());
                
                try {
                    sendMessage(requesterSession, errorResponse);
                } catch (Exception sendException) {
                    log.error("发送错误信息给用户 {} 失败", userId, sendException);
                }
            }
        }
    }
    
    /**
     * 处理标记单个呼救请求为已读
     */
    private void handleMarkSosRequestAsRead(Long userId, Map<String, Object> data) {
        try {
            log.info("开始处理用户 {} 标记呼救请求为已读", userId);
            
            // 获取请求参数
            Object sosIdObj = data.get("sosId");
            if (sosIdObj == null) {
                throw new RuntimeException("sosId不能为空");
            }
            
            Long sosId = Long.valueOf(sosIdObj.toString());
            
            // 验证SOS请求存在且由当前用户发起
            SosRequest sosRequest = sosRequestRepository.findById(sosId)
                    .orElseThrow(() -> new RuntimeException("SOS请求不存在"));
            
            if (!sosRequest.getUserId().equals(userId)) {
                throw new RuntimeException("无权操作此SOS请求");
            }
            
            // 更新为已读状态
            sosRequest.setIsRead(1);
            sosRequestRepository.save(sosRequest);
            
            // 发送处理结果给用户
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> response = new HashMap<>();
                response.put("type", "标记呼救请求已读结果");
                response.put("message", "呼救请求已标记为已读");
                response.put("sosId", sosId);
                response.put("timestamp", System.currentTimeMillis());
                
                try {
                    sendMessage(requesterSession, response);
                    log.info("已向用户 {} 发送标记已读结果，SOS ID: {}", userId, sosId);
                } catch (Exception e) {
                    log.error("发送标记已读结果给用户 {} 失败", userId, e);
                }
            }
        } catch (Exception e) {
            log.error("处理标记呼救请求为已读失败", e);
            
            // 向用户发送错误信息
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("type", "错误");
                errorResponse.put("message", "标记已读处理失败: " + e.getMessage());
                
                try {
                    sendMessage(requesterSession, errorResponse);
                } catch (Exception sendException) {
                    log.error("发送错误信息给用户 {} 失败", userId, sendException);
                }
            }
        }
    }
    
    /**
     * 处理隐藏单个呼救请求
     */
    private void handleHideSosRequest(Long userId, Map<String, Object> data) {
        try {
            log.info("开始处理用户 {} 隐藏呼救请求", userId);
            
            // 获取请求参数
            Object sosIdObj = data.get("sosId");
            if (sosIdObj == null) {
                throw new RuntimeException("sosId不能为空");
            }
            
            Long sosId = Long.valueOf(sosIdObj.toString());
            
            // 验证SOS请求存在且由当前用户发起
            SosRequest sosRequest = sosRequestRepository.findById(sosId)
                    .orElseThrow(() -> new RuntimeException("SOS请求不存在"));
            
            if (!sosRequest.getUserId().equals(userId)) {
                throw new RuntimeException("无权操作此SOS请求");
            }
            
            // 更新为隐藏状态
            sosRequest.setIsHidden(1);
            sosRequestRepository.save(sosRequest);
            
            // 发送处理结果给用户
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> response = new HashMap<>();
                response.put("type", "标记呼救请求隐藏结果");
                response.put("message", "呼救请求已标记为隐藏");
                response.put("sosId", sosId);
                response.put("timestamp", System.currentTimeMillis());
                
                try {
                    sendMessage(requesterSession, response);
                    log.info("已向用户 {} 发送标记隐藏结果，SOS ID: {}", userId, sosId);
                } catch (Exception e) {
                    log.error("发送标记隐藏结果给用户 {} 失败", userId, e);
                }
            }
        } catch (Exception e) {
            log.error("处理隐藏呼救请求失败", e);
            
            // 向用户发送错误信息
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("type", "错误");
                errorResponse.put("message", "标记隐藏处理失败: " + e.getMessage());
                
                try {
                    sendMessage(requesterSession, errorResponse);
                } catch (Exception sendException) {
                    log.error("发送错误信息给用户 {} 失败", userId, sendException);
                }
            }
        }
    }
    
    /**
     * 处理标记收到的呼救请求为已读
     */
    private void handleMarkReceivedSosRequestAsRead(Long userId, Map<String, Object> data) {
        try {
            log.info("开始处理用户 {} 标记收到的呼救请求为已读", userId);
            
            // 获取请求参数
            Object sosIdObj = data.get("sosId");
            if (sosIdObj == null) {
                throw new RuntimeException("sosId不能为空");
            }
            
            Long sosId = Long.valueOf(sosIdObj.toString());
            
            // 验证SOS请求存在且用户是帮助者
            SosHelper sosHelper = sosHelperRepository.findBySosIdAndHelperId(sosId, userId)
                    .orElseThrow(() -> new RuntimeException("您未被邀请参与此SOS请求"));
            
            // 更新为已读状态
            sosHelper.setIsRead(1);
            sosHelperRepository.save(sosHelper);
            
            // 发送处理结果给用户
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> response = new HashMap<>();
                response.put("type", "标记收到的呼救请求已读结果");
                response.put("message", "收到的呼救请求已标记为已读");
                response.put("sosId", sosId);
                response.put("timestamp", System.currentTimeMillis());
                
                try {
                    sendMessage(requesterSession, response);
                    log.info("已向用户 {} 发送标记收到的呼救请求已读结果，SOS ID: {}", userId, sosId);
                } catch (Exception e) {
                    log.error("发送标记收到的呼救请求已读结果给用户 {} 失败", userId, e);
                }
            }
        } catch (Exception e) {
            log.error("处理标记收到的呼救请求为已读失败", e);
            
            // 向用户发送错误信息
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("type", "错误");
                errorResponse.put("message", "标记收到的呼救请求已读处理失败: " + e.getMessage());
                
                try {
                    sendMessage(requesterSession, errorResponse);
                } catch (Exception sendException) {
                    log.error("发送错误信息给用户 {} 失败", userId, sendException);
                }
            }
        }
    }
    
    /**
     * 处理隐藏收到的呼救请求
     */
    private void handleHideReceivedSosRequest(Long userId, Map<String, Object> data) {
        try {
            log.info("开始处理用户 {} 隐藏收到的呼救请求", userId);
            
            // 获取请求参数
            Object sosIdObj = data.get("sosId");
            if (sosIdObj == null) {
                throw new RuntimeException("sosId不能为空");
            }
            
            Long sosId = Long.valueOf(sosIdObj.toString());
            
            // 验证SOS请求存在且用户是帮助者
            SosHelper sosHelper = sosHelperRepository.findBySosIdAndHelperId(sosId, userId)
                    .orElseThrow(() -> new RuntimeException("您未被邀请参与此SOS请求"));
            
            // 更新为隐藏状态
            sosHelper.setIsHidden(1);
            sosHelperRepository.save(sosHelper);
            
            // 发送处理结果给用户
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> response = new HashMap<>();
                response.put("type", "标记收到的呼救请求隐藏结果");
                response.put("message", "收到的呼救请求已标记为隐藏");
                response.put("sosId", sosId);
                response.put("timestamp", System.currentTimeMillis());
                
                try {
                    sendMessage(requesterSession, response);
                    log.info("已向用户 {} 发送标记收到的呼救请求隐藏结果，SOS ID: {}", userId, sosId);
                } catch (Exception e) {
                    log.error("发送标记收到的呼救请求隐藏结果给用户 {} 失败", userId, e);
                }
            }
        } catch (Exception e) {
            log.error("处理隐藏收到的呼救请求失败", e);
            
            // 向用户发送错误信息
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("type", "错误");
                errorResponse.put("message", "标记收到的呼救请求隐藏处理失败: " + e.getMessage());
                
                try {
                    sendMessage(requesterSession, errorResponse);
                } catch (Exception sendException) {
                    log.error("发送错误信息给用户 {} 失败", userId, sendException);
                }
            }
        }
    }

    /**
     * 处理一键已读收到的呼救请求
     */
    private void handleMarkAllReceivedSosRequestsAsRead(Long userId, Map<String, Object> data) {
        try {
            log.info("开始处理用户 {} 的一键已读收到的呼救请求", userId);
            
            // 将该用户作为帮助者参与的所有SOS请求标记为已读
            List<SosHelper> sosHelpers = sosHelperRepository.findByHelperId(userId);
            int updatedCount = 0;
            
            for (SosHelper sosHelper : sosHelpers) {
                // 只更新未读的请求
                if (sosHelper.getIsRead() == 0) {
                    sosHelper.setIsRead(1);
                    sosHelperRepository.save(sosHelper);
                    updatedCount++;
                }
            }
            
            // 发送处理结果给用户
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> response = new HashMap<>();
                response.put("type", "一键已读收到的呼救请结果");
                response.put("message", "成功将 " + updatedCount + " 条收到的呼救请求标记为已读");
                response.put("updatedCount", updatedCount);
                response.put("timestamp", System.currentTimeMillis());
                
                try {
                    sendMessage(requesterSession, response);
                    log.info("已向用户 {} 发送一键已读收到的呼救请求处理结果，共更新 {} 条记录", userId, updatedCount);
                } catch (Exception e) {
                    log.error("发送一键已读收到的呼救请求处理结果给用户 {} 失败", userId, e);
                }
            }
        } catch (Exception e) {
            log.error("处理一键已读收到的呼救请求失败", e);
            
            // 向用户发送错误信息
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("type", "错误");
                errorResponse.put("message", "一键已读收到的呼救请求处理失败: " + e.getMessage());
                
                try {
                    sendMessage(requesterSession, errorResponse);
                } catch (Exception sendException) {
                    log.error("发送错误信息给用户 {} 失败", userId, sendException);
                }
            }
        }
    }
    
    /**
     * 处理一键隐藏收到的呼救请求
     */
    private void handleHideAllReceivedSosRequests(Long userId, Map<String, Object> data) {
        try {
            log.info("开始处理用户 {} 的一键隐藏收到的呼救请求", userId);
            
            // 将该用户作为帮助者参与的所有SOS请求标记为隐藏
            List<SosHelper> sosHelpers = sosHelperRepository.findByHelperId(userId);
            int hiddenCount = 0;
            
            for (SosHelper sosHelper : sosHelpers) {
                // 只更新未隐藏的请求
                if (sosHelper.getIsHidden() == 0) {
                    sosHelper.setIsHidden(1);
                    sosHelperRepository.save(sosHelper);
                    hiddenCount++;
                }
            }
            
            // 发送处理结果给用户
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> response = new HashMap<>();
                response.put("type", "一键隐藏收到的呼救请结果");
                response.put("message", "成功将 " + hiddenCount + " 条收到的呼救请求标记为隐藏");
                response.put("hiddenCount", hiddenCount);
                response.put("timestamp", System.currentTimeMillis());
                
                try {
                    sendMessage(requesterSession, response);
                    log.info("已向用户 {} 发送一键隐藏收到的呼救请求处理结果，共隐藏 {} 条记录", userId, hiddenCount);
                } catch (Exception e) {
                    log.error("发送一键隐藏收到的呼救请求处理结果给用户 {} 失败", userId, e);
                }
            }
        } catch (Exception e) {
            log.error("处理一键隐藏收到的呼救请求失败", e);
            
            // 向用户发送错误信息
            WebSocketSession requesterSession = getUserSession(userId);
            if (requesterSession != null && requesterSession.isOpen()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("type", "错误");
                errorResponse.put("message", "一键隐藏收到的呼救请求处理失败: " + e.getMessage());
                
                try {
                    sendMessage(requesterSession, errorResponse);
                } catch (Exception sendException) {
                    log.error("发送错误信息给用户 {} 失败", userId, sendException);
                }
            }
        }
    }

    // 获取默认内容
    private String getDefaultContent(Integer status) {
        switch (status) {
            case 1:
                return "已接受请求";
            case 2:
                return "已拒绝请求";
            case 3:
                return "正在前往";
            case 4:
                return "已解决";
            default:
                return "未知状态";
        }
    }

    /**
     * 初始化群聊
     */
    private void initializeChatGroup(Long sosId, Long requesterId, Long firstHelperId) {
        try {
            // 创建群聊组
            chatGroups.putIfAbsent(sosId, ConcurrentHashMap.newKeySet());
            Set<Long> participants = chatGroups.get(sosId);
            
            // 添加求助者和第一个帮助者
            participants.add(requesterId);
            participants.add(firstHelperId);
            
            // 初始化消息历史
            chatMessages.putIfAbsent(sosId, new ArrayList<>());
            
            log.info("已为SOS {} 初始化群聊，参与者: 求助者 {}, 第一个帮助者 {}", sosId, requesterId, firstHelperId);
            
            // 通知所有参与者群聊已创建
            notifyChatGroupCreated(sosId, participants);
        } catch (Exception e) {
            log.error("初始化群聊失败: sosId={}, requesterId={}, firstHelperId={}", sosId, requesterId, firstHelperId, e);
        }
    }
    
    /**
     * 通知群聊创建
     */
    private void notifyChatGroupCreated(Long sosId, Set<Long> participants) {
        Map<String, Object> notification = Map.of(
            "type", "群聊创建通知",
            "sosId", sosId,
            "message", "救援群聊已创建，您可以开始交流了",
            "timestamp", System.currentTimeMillis()
        );
        
        // 通知所有参与者
        for (Long participantId : participants) {
            WebSocketSession session = getUserSession(participantId);
            if (session != null && session.isOpen()) {
                try {
                    sendMessage(session, notification);
                    log.info("已通知用户 {} 群聊创建", participantId);
                } catch (Exception e) {
                    log.error("通知用户 {} 群聊创建失败", participantId, e);
                }
            }
        }
    }
    
    /**
     * 添加新成员到群聊（当更多帮助者接受请求时）
     */
    private void addMemberToChatGroup(Long sosId, Long newHelperId) {
        try {
            Set<Long> participants = chatGroups.get(sosId);
            if (participants != null) {
                participants.add(newHelperId);
                
                // 通知新成员加入
                Map<String, Object> joinNotification = Map.of(
                    "type", "新成员加入",
                    "sosId", sosId,
                    "userId", newHelperId,
                    "message", "新帮助者加入了群聊",
                    "timestamp", System.currentTimeMillis()
                );
                
                // 通知所有现有成员有新成员加入
                for (Long participantId : participants) {
                    WebSocketSession session = getUserSession(participantId);
                    if (session != null && session.isOpen()) {
                        try {
                            sendMessage(session, joinNotification);
                            log.info("已通知用户 {} 有新成员加入群聊", participantId);
                        } catch (Exception e) {
                            log.error("通知用户 {} 有新成员加入群聊失败", participantId, e);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("添加新成员到群聊失败: sosId={}, newHelperId={}", sosId, newHelperId, e);
        }
    }
    
    // 获取状态描述
    private String getStatusDescription(Integer status) {
        switch (status) {
            case 1:
                return "已接受";
            case 2:
                return "已拒绝";
            case 3:
                return "前往中";
            case 4:
                return "已解决";
            default:
                return "未知状态";
        }
    }

    // 解析status字段值
    private Integer parseStatusValue(Object statusObj) {
        if (statusObj instanceof Integer) {
            return (Integer) statusObj;
        } else if (statusObj instanceof String) {
            try {
                return Integer.parseInt((String) statusObj);
            } catch (NumberFormatException e) {
                // 如果无法解析为整数，返回默认值1（医疗类型）
                log.warn("无法将字符串 '{}' 解析为整数，使用默认值1", statusObj);
                return 1;
            }
        } else {
            // 如果既不是整数也不是字符串，返回默认值1
            log.warn("type/status字段格式错误，使用默认值1");
            return 1;
        }
    }

    // 获取用户会话
    private WebSocketSession getUserSession(Long userId) {
        return userSessions.values().stream()
                .filter(session -> sessionUserMap.get(session.getId()).equals(userId))
                .findFirst()
                .orElse(null);
    }

    // 发送消息
    private void sendMessage(WebSocketSession session, Map<String, Object> message) throws Exception {
        String payload = objectMapper.writeValueAsString(message);
        session.sendMessage(new TextMessage(payload));
    }

    // 创建消息
    private Map<String, Object> createMessage(String type, String message) {
        return Map.of(
            "type", type,
            "message", message,
            "timestamp", System.currentTimeMillis()
        );
    }
    
    /**
     * 创建带用户信息的消息
     */
    private Map<String, Object> createMessage(String type, String content, Map<String, Object> userInfo) {
        return Map.of(
            "type", type,
            "content", content,
            "timestamp", System.currentTimeMillis(),
            "userInfo", userInfo
        );
    }
    
    /**
     * 处理群聊消息
     */
    private void handleGroupChatMessage(Long userId, Map<String, Object> data) {
        try {
            Object sosIdObj = data.get("sosId");
            Object messageObj = data.get("message");
            
            if (sosIdObj == null || messageObj == null) {
                throw new RuntimeException("sosId和消息内容不能为空");
            }
            
            Long sosId = Long.valueOf(sosIdObj.toString());
            String message = messageObj.toString();
            
            // 验证用户是否在群聊中
            Set<Long> participants = chatGroups.get(sosId);
            if (participants == null || !participants.contains(userId)) {
                throw new RuntimeException("您不在该群聊中");
            }
            
            // 获取发送者信息
            User sender = userRepository.findById(userId)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            // 创建消息
            Map<String, Object> chatMessage = new HashMap<>();
            chatMessage.put("type", "群聊消息");
            chatMessage.put("sosId", sosId);
            chatMessage.put("userId", userId);
            chatMessage.put("username", sender.getUsername());
            chatMessage.put("realName", sender.getRealName());
            chatMessage.put("avatar", sender.getAvatar());
            chatMessage.put("message", message);
            chatMessage.put("timestamp", System.currentTimeMillis());
            
            // 保存消息到历史记录
            List<Map<String, Object>> messages = chatMessages.computeIfAbsent(sosId, k -> new ArrayList<>());
            messages.add(chatMessage);
            
            // 转发消息给所有参与者
            for (Long participantId : participants) {
                // 不需要转发给自己
                if (!participantId.equals(userId)) {
                    WebSocketSession session = getUserSession(participantId);
                    if (session != null && session.isOpen()) {
                        try {
                            sendMessage(session, chatMessage);
                            log.info("已转发群聊消息给用户 {}", participantId);
                        } catch (Exception e) {
                            log.error("转发群聊消息给用户 {} 失败", participantId, e);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("处理群聊消息失败: userId={}, data={}", userId, data, e);
            
            // 向发送者发送错误信息
            WebSocketSession senderSession = getUserSession(userId);
            if (senderSession != null && senderSession.isOpen()) {
                try {
                    sendMessage(senderSession, Map.of(
                        "type", "错误",
                        "message", "发送消息失败: " + e.getMessage()
                    ));
                } catch (Exception sendException) {
                    log.error("发送错误信息给用户 {} 失败", userId, sendException);
                }
            }
        }
    }
    
    /**
     * 处理获取群聊历史消息
     */
    private void handleGetChatHistory(Long userId, Map<String, Object> data) {
        try {
            Object sosIdObj = data.get("sosId");
            if (sosIdObj == null) {
                throw new RuntimeException("sosId不能为空");
            }
            
            Long sosId = Long.valueOf(sosIdObj.toString());
            
            // 验证用户是否在群聊中
            Set<Long> participants = chatGroups.get(sosId);
            if (participants == null || !participants.contains(userId)) {
                throw new RuntimeException("您不在该群聊中");
            }
            
            // 获取历史消息
            List<Map<String, Object>> messages = chatMessages.getOrDefault(sosId, new ArrayList<>());
            
            // 发送历史消息给用户
            WebSocketSession session = getUserSession(userId);
            if (session != null && session.isOpen()) {
                Map<String, Object> response = new HashMap<>();
                response.put("type", "群聊历史消息");
                response.put("sosId", sosId);
                response.put("messages", messages);
                response.put("count", messages.size());
                response.put("timestamp", System.currentTimeMillis());
                
                try {
                    sendMessage(session, response);
                    log.info("已发送群聊历史消息给用户 {}，共 {} 条消息", userId, messages.size());
                } catch (Exception e) {
                    log.error("发送群聊历史消息给用户 {} 失败", userId, e);
                }
            }
        } catch (Exception e) {
            log.error("处理获取群聊历史消息失败: userId={}, data={}", userId, data, e);
            
            // 向用户发送错误信息
            WebSocketSession session = getUserSession(userId);
            if (session != null && session.isOpen()) {
                try {
                    sendMessage(session, Map.of(
                        "type", "错误",
                        "message", "获取历史消息失败: " + e.getMessage()
                    ));
                } catch (Exception sendException) {
                    log.error("发送错误信息给用户 {} 失败", userId, sendException);
                }
            }
        }
    }
    
    /**
     * 向特定用户发送消息
     */
    public void sendToUser(Long userId, Map<String, Object> message) {
        try {
            log.info("准备向用户 {} 发送WebSocket消息: {}", userId, message);
            WebSocketSession session = getUserSession(userId);
            if (session != null && session.isOpen()) {
                log.info("找到用户 {} 的WebSocket会话，会话ID: {}", userId, session.getId());
                sendMessage(session, message);
                log.info("成功向用户 {} 发送WebSocket消息，消息类型: {}", userId, message.get("type"));
            } else {
                if (session == null) {
                    log.warn("未找到用户 {} 的WebSocket会话", userId);
                } else if (!session.isOpen()) {
                    log.warn("用户 {} 的WebSocket会话已关闭", userId);
                }
            }
        } catch (Exception e) {
            log.error("向用户 {} 发送消息失败，消息内容: {}", userId, message, e);
        }
    }
}